package pt.iscte.daam.model;

import java.util.Calendar;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import org.apache.log4j.Logger;

public class DdlGenerator {

	private static final Logger logger = Logger.getLogger(DdlGenerator.class);
	final String persistenceUnitName = "CustomerService";
	EntityManagerFactory factory;

	public DdlGenerator() {
		factory = Persistence.createEntityManagerFactory(persistenceUnitName);
	}

	public void close() {
		factory.close();
	}

	public static void main(String[] args) {
		logger.info("update schema");
		DdlGenerator ddlGenerator = new DdlGenerator();

		//ddlGenerator.query();
		
		Senhorio senhorio = ddlGenerator.criarSenhorio("tiagomistral");
		ddlGenerator.adicionarImovel(senhorio);

		// ddlGenerator.adicionarCustomerRandom();
		// ddlGenerator.adicionarCustomer();
		// ddlGenerator.adicionarActor();
		// ddlGenerator.updateActor(ddlGenerator.carregaActor());

		ddlGenerator.close();
		logger.info("updated");
	}

	private void adicionarImovel(Senhorio senhorio) {
		EntityManager manager = factory.createEntityManager();
		
		senhorio = manager.find(Senhorio.class, senhorio.getUtilizador());

		Imovel imovel = new Imovel();
		imovel.setConselho("Conselho");
		imovel.setDetalhe("Imovel do puto");
		senhorio.adicionaImovel(imovel);

		
		
		Quarto quarto = new Quarto();
		quarto.setDataCriacao(Calendar.getInstance());
		quarto.setPreco(200f);
		quarto.setImovel(imovel);
		
		manager.getTransaction().begin();
		manager.persist(imovel);
		manager.persist(quarto);
		manager.getTransaction().commit();

		manager.close();

	}

	private Senhorio criarSenhorio(String user) {
		EntityManager manager = factory.createEntityManager();

		Senhorio find = manager.find(Senhorio.class, user);

		if (find == null) {
			find = new Senhorio();
			find.setUtilizador(user);
			find.setPrimeiroNome("Tiago");
			find.setUltimoNome("Santos");

			manager.getTransaction().begin();
			manager.persist(find);
			manager.getTransaction().commit();
		}
		manager.close();
		return find;
	}
	
	private void query(){
		EntityManager entityManager = factory.createEntityManager();
		TypedQuery<Quarto> query = entityManager.createNamedQuery("Quarto.findAll", Quarto.class);
		List<Quarto> results = query.getResultList();
		
		for(Quarto q: results){
			System.out.println(q.getId());
			System.out.println(q.getImovel().getSenhorio().getUltimoNome());
		}
		
		entityManager.close();
	}

}
